package com.naiterui.ehp.bs.doctor.utils;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.encypt.RSAUtil;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import org.apache.commons.lang3.StringUtils;

public class ChackPasswordUtils {

    /**
     * 密码规则校验
     *
     * @param password pw
     *
     * @return true-success
     */
    public static boolean validatePassword(String password) {
        String regex = "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]))(?=^[^\u4e00-\u9fa5]{0,}$).{9,}$";
        return password.matches(regex);
    }

    public static String validPwd(String phoneNum, String password) throws BusinessException {

        // 密码解密
        String pwd = decryptPasswd(password);
        if (!LimitValueConfig.validateLimit(LimitValueConfig.LIMIT_PASSWORD, pwd)) {
            throw new BusinessException(ExceptionCodes.REGIST_PWD_ERROR);
        }
        return pwd;
    }

    public static void main(String[] args) {
        System.out.println(ChackPasswordUtils.validatePassword("abcd"));
    }

    /**
     * 解密密码
     * @param password
     * @return
     * @throws BusinessException
     */
    public static String decryptPasswd(String password) throws BusinessException{
        // 1.密码非空判断
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException(ExceptionCodes.REGIST_PWD_NULL);
        }
        // 2.密码解密
        String pwd = "";
        try {
            password = password.replaceAll(" ", "+");
            pwd = RSAUtil.decryptByPrivateKey(password);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCodes.REGIST_PWD_ERROR);
        }
        // 3.解密后密码是否为空
        if (pwd == null || "".equals(pwd)) {
            throw new BusinessException(ExceptionCodes.REGIST_PWD_NULL);
        }
        pwd = pwd.trim();
        return pwd;
    }
}
